package com.demo.user.controller;

import com.demo.common.vo.Result;
import com.demo.user.pojo.User;
import com.demo.user.service.UserService;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Result login(User param, @RequestParam("captcha")String captcha, HttpServletRequest request ,HttpSession session) {
        if (!CaptchaUtil.ver(captcha, request)) {
            return Result.fail("验证码错误");
        }

        User user = userService.login(param);

        if (user != null) {
            /**
             * BCryptPasswordEncoder 对象是Spring Security提供的密码加密工具类，可以自动提供加盐，无需自己保存盐值
             * 而MD5容易被人猜测，所以不推荐使用，这里使用BCryptPasswordEncoder
             */
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            /*数据1是请求密码的值，数据2是数据库中保存的加密密码的值*/
            boolean matches = bCryptPasswordEncoder.matches(param.getPassword(), user.getPassword());
            if (matches) {
                user.setPassword(null); // 密码不返回给前端
                session.setAttribute("userInfo", user); // 将用户信息放入session
                return Result.success(); // 登录成功
            }
        }

        return Result.fail("用户名或密码错误");

    }

}
